#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QFileDialog>
#include<QDebug>
#include<fstream>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QMenuBar* menuBar = new QMenuBar(this);
    this->setMenuBar(menuBar);
    QMenu* menu = new QMenu("文件");
     menuBar->addMenu(menu);
     QAction* action1 = new QAction("保存");
      QAction* action2 = new QAction("加载");
      menu->addAction(action1);
      menu->addAction(action2);
     edit = new QTextEdit(this);
     this->setCentralWidget(edit);
     edit->setPlaceholderText("此处编写⽂本内容...");
     connect(action1, &QAction::triggered, this, &MainWindow::save);
     connect(action2, &QAction::triggered, this, &MainWindow::load);


}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::save()
{
    QFileDialog* dialog = new QFileDialog(this);
    QString fileName = dialog->getSaveFileName(this, "保存文件", "C:/Users/1/");
     qDebug() << "fileName: " << fileName;
     std::ofstream file(fileName.toStdString().c_str());
      if (!file.is_open()) {
      qDebug() << "⽂件保存失败!";
      return;
      }
      const QString& text = edit->toPlainText();
      file << text.toStdString();
      file.close();
}
void MainWindow::load()
{

    QFileDialog* dialog = new QFileDialog(this);
    QString fileName = dialog->getOpenFileName(this, "加载⽂件", "C:/Users/1/");
     qDebug() << "fileName: " << fileName;
     std::ifstream file(fileName.toStdString().c_str());
      if (!file.is_open()) {
      qDebug() << "⽂件加载失败!";
      return;
      }
      std::string content;
      std::string line;
      while (std::getline(file, line)) {
      content += line;
      content += "\n";
      }
      file.close();
      QString text = QString::fromStdString(content);
       edit->setPlainText(text);

}

